<div id="app"></div>
<script>
  let activeEffect = null;
  class Dep {
    subscribers = new Set();

    depend() {
      if (activeEffect) {
        this.subscribers.add(activeEffect);
      }
    }
    notify() {
      this.subscribers.forEach((effect) => effect());
    }
  }
  function watchEffect(effect) {
    activeEffect = effect;
    effect();
    activeEffect = null;
  }

  function reactive(raw) {
    // 获取对象key
    Object.keys(raw).forEach((key) => {
      let value = raw[key];
      let dep = new Dep();
      Object.defineProperty(raw, key, {
        get() {
          dep.depend();
          return value;
        },
        set(newValue) {
          // 先进行 赋值
          value = newValue;
          // 再进行更新
          dep.notify();
        },
      });
    });
    return raw;
  }

  let state = reactive({
    count: 0,
  });

  watchEffect(() => {
    console.log(state.count);
  });
  state.count++;
</script>
